package com.ruoyi.business.controller;

import com.alibaba.fastjson2.JSON;
import com.github.kevinsawicki.http.HttpRequest;
import com.google.gson.Gson;
import com.ruoyi.business.domain.DisplayVideo;
import com.ruoyi.business.domain.ViolationCategory;
import com.ruoyi.business.dto.EditEnterpriseDTO;
import com.ruoyi.business.service.IDisplayVideoService;
import com.ruoyi.business.service.IViolationCategoryService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.lczUtils.ApiHttp;
import com.ruoyi.common.wxpay.WxPayConfig;
import com.ruoyi.framework.web.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.ObjectUtils;
import springfox.documentation.annotations.ApiIgnore;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.Enterprise;
import com.ruoyi.business.service.IEnterpriseService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 企业Controller
 * 
 * @author lcz
 * @date 2025-01-19
 */
@Api(tags = "企业相关接口")
@RestController
@RequestMapping("/business/enterprise")
public class EnterpriseController extends BaseController
{
    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IViolationCategoryService violationCategoryService;

    @Autowired
    private IDisplayVideoService displayVideoService;

    /**
     * 查询企业列表
     */
    @ApiIgnore
    @PreAuthorize("@ss.hasPermi('business:enterprise:list')")
    @GetMapping("/list")
    public TableDataInfo list(Enterprise enterprise)
    {
        startPage();
        List<Enterprise> list = enterpriseService.selectEnterpriseList(enterprise);
        return getDataTable(list);
    }

    /**
     * 导出企业列表
     */
    @ApiIgnore
    @PreAuthorize("@ss.hasPermi('business:enterprise:export')")
    @Log(title = "企业", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Enterprise enterprise)
    {
        List<Enterprise> list = enterpriseService.selectEnterpriseList(enterprise);
        ExcelUtil<Enterprise> util = new ExcelUtil<Enterprise>(Enterprise.class);
        util.exportExcel(response, list, "企业数据");
    }

    /**
     * 获取企业详细信息
     */
    @ApiIgnore
    @PreAuthorize("@ss.hasPermi('business:enterprise:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(enterpriseService.selectEnterpriseById(id));
    }

    /**
     * 新增企业
     */
    @ApiIgnore
    @PreAuthorize("@ss.hasPermi('business:enterprise:add')")
    @Log(title = "企业", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Enterprise enterprise)
    {
        return toAjax(enterpriseService.insertEnterprise(enterprise));
    }

    /**
     * 修改企业
     */
    @ApiIgnore
    @PreAuthorize("@ss.hasPermi('business:enterprise:edit')")
    @Log(title = "企业", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Enterprise enterprise)
    {
        return toAjax(enterpriseService.updateEnterprise(enterprise));
    }

    /**
     * 删除企业
     */
    @ApiIgnore
    @PreAuthorize("@ss.hasPermi('business:enterprise:remove')")
    @Log(title = "企业", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(enterpriseService.deleteEnterpriseByIds(ids));
    }

    /** 前端接口 ***************************************************************************************************/
    /** 前端接口 ***************************************************************************************************/
    /** 前端接口 ***************************************************************************************************/

//    /**
//     * 查询企业列表
//     * 接口路径：/enterprise/front/list
//     */
//    @GetMapping("/front/list")
//    @ApiOperation("前台查询企业列表")
//    public TableDataInfo frontList(Enterprise enterprise)
//    {
//        startPage();
//        List<Enterprise> list = enterpriseService.selectEnterpriseList(enterprise);
//        return getDataTable(list);
//    }

    /**
     * 获取企业详情接口
     * 接口路径：/enterprise/front/info
     */
    @ApiOperation(value = "获取企业详情接口(可查询是否有违规记录)")
    @GetMapping(value = "/front/info")
    public R<Enterprise> frontInfo()
    {
        Long id = tokenService.getUserId();
        Enterprise enterprise = enterpriseService.selectEnterpriseById(id);
        if (ObjectUtils.isEmpty(enterprise)){
            return R.fail("企业不存在");
        }
        if (!ObjectUtils.isEmpty(enterprise.getViolationCategoryId())) {
            ViolationCategory violationCategory = violationCategoryService.selectViolationCategoryById(enterprise.getViolationCategoryId());
            if (!ObjectUtils.isEmpty(violationCategory)){
                enterprise.setCategoryIntegral(violationCategory.getIntegral());
            }
        }
        enterprise.setId(null);
        enterprise.setSessionkey(null);
        enterprise.setOpenId(null);
        return R.ok(enterprise);
    }

//    /**
//     * 新增企业
//     * 接口路径：/enterprise/front/add
//     */
//    @ApiOperation("前台新增企业")
//    @PostMapping("/front/add")
//    public AjaxResult frontAdd(@RequestBody Enterprise enterprise)
//    {
//        return toAjax(enterpriseService.insertEnterprise(enterprise));
//    }

    /**
     * 修改企业
     * 接口路径：/enterprise/front/edit
     */
    @ApiOperation("企业信息提交接口/企业信息修改接口")
    @PostMapping("/front/edit")
    public AjaxResult frontEdit(@RequestBody EditEnterpriseDTO dto)
    {
        Long enterpriseId = tokenService.getUserId();
        dto.setId(enterpriseId);
        return enterpriseService.frontEdit(dto);
    }

//    /**
//     * 删除企业
//     * 接口路径：/enterprise/front/delete
//     */
//    @ApiOperation("前台删除企业")
//    @GetMapping("/front/delete")
//    public AjaxResult frontRemove(@RequestParam Long[] ids)
//    {
//        return toAjax(enterpriseService.deleteEnterpriseByIds(ids));
//    }
    /**
     * 微信登录
     * @param jscode
     *
     * @return
     */
    @ApiOperation("微信授权登录接口")
    @GetMapping("/front/wxLogin")
    public R<Enterprise> WXlogin(@RequestParam("jscode") String jscode) {
//        WxPayConfig wxPayConfig = new WxPayConfig();
//        String appid = wxPayConfig.getAppId();
//        String secret = wxPayConfig.getAppKey();
        String appid = "wx21022e0a199763b8";
        String secret = "3d8b1df49682d995c898bb96512dbfc4";
//        String appid = "wx9e05124494fa148d";
//        String secret = "c51634d450b2f868e67fa30426ceb94f";

        //获取用户openid
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + jscode + "&grant_type=authorization_code";
        HttpRequest request = ApiHttp.getEE(url);
        String body = request.body();
        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<String, Object>();
        map = gson.fromJson(body, map.getClass());
        String openId;
        String sessionkey;
        if (map.containsKey("openid")) {
            openId = map.get("openid").toString();
            sessionkey = map.get("session_key").toString();
        } else {
            return R.fail("登录异常，请重新登录！");
        }

        Enterprise enterprise = new Enterprise();
        enterprise.setOpenId(openId);
        List<Enterprise> enterpriseList = enterpriseService.selectEnterpriseList(enterprise);
        String enterpriseName = "";
        boolean isPhone = false;
        if (enterpriseList.size() > 0) {
            enterprise = enterpriseList.get(0);
            enterpriseName = enterprise.getEnterpriseName();
//            isPhone = ObjectUtils.isEmpty(enterprise.getContactPhone())?false:true;
        } else {
            enterprise.setSessionkey(sessionkey);
            enterprise.setEnterpriseName("");
            enterprise.setIntegral(0l);
            enterpriseService.insertEnterprise(enterprise);
        }

        //生成token
        LoginUser loginUser = new LoginUser();
        SysUser sysUser = new SysUser();
        sysUser.setUserId(enterprise.getId().longValue());
        sysUser.setUserName(enterpriseName);
        sysUser.setOpenId(openId);
        sysUser.setSessionkey(sessionkey);
        loginUser.setUser(sysUser);
        String token = tokenService.createToken(loginUser);

        enterprise.setToken(token);
        enterpriseService.updateEnterprise(enterprise);
        enterprise.setId(null);
        enterprise.setSessionkey(null);
        enterprise.setOpenId(null);

        DisplayVideo displayVideo = displayVideoService.selectDisplayVideoById(1l);
        enterprise.setIsDisplayVideo(displayVideo.getIsDisplayVideo()==1?true:false);

        return R.ok(enterprise);
    }

    /**
     * 获取是否显示视频
     * @return
     */
    @ApiOperation(value = "获取是否显示视频")
    @GetMapping("/getDisplayVideo")
    public R getDisplayVideo() {
        DisplayVideo displayVideo = displayVideoService.selectDisplayVideoById(1l);
        return R.ok(displayVideo.getIsDisplayVideo()==1?true:false);
    }
}
